package org.andolphin.client;

import org.andolphin.client.Andolphin.Prefs;
import org.andolphin.client.utils.DateUtils;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class WordActivity extends Activity{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.word);
        this.checkRegister();
    }

    private void checkRegister() {
        SharedPreferences prefs = this.getSharedPreferences(Andolphin.Prefs.ANDOLPHIN, Prefs.MODE);
        String username = prefs.getString(Andolphin.Prefs.USERNAME, null);
        String password = prefs.getString(Andolphin.Prefs.PASSWORD, null);
        long expire = prefs.getLong(Andolphin.Prefs.EXPIRE, -1);

        if (username == null || password == null) {
            Intent intent = new Intent(Andolphin.Intent.LOGIN);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            this.startActivity(intent);
        } else {
            if(DateUtils.nowInMillis() >= expire){
                Toast.makeText(this, "expired", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        Intent intent;
        switch (item.getItemId()) {
        case R.id.config:
            intent = new Intent(Andolphin.Intent.CONFIG);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            this.startActivity(intent);
            break;
        case R.id.login:
            intent = new Intent(Andolphin.Intent.LOGIN);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            this.startActivity(intent);
            break;
        case R.id.register:
            intent = new Intent(Andolphin.Intent.REGISTER);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            this.startActivity(intent);
            break;
        case R.id.exit:
            doSystemExit();
            break;
        }
        return false;
    }

    private void doSystemExit() {
        this.finish();
    }
}